package com.example.testapp.ui.mine

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.testapp.R
import com.example.testapp.config.ApiProviderManager
import com.google.android.material.bottomsheet.BottomSheetDialog

/**
 * 服务提供商选择器底部弹窗
 * 仅提供预设服务提供商列表
 */
class ProviderPickerDialog(
    context: Context, 
    providers: List<String>, 
    title: String?
) : BottomSheetDialog(context) {
    
    // UI组件
    private lateinit var recyclerView: RecyclerView
    private lateinit var tvTitle: TextView
    private lateinit var tvCancel: TextView
    private lateinit var tvConfirm: TextView
    private lateinit var etSearch: EditText
    
    // 数据
    private val allProviders: List<String> = ArrayList(providers)
    private val filteredProviders: MutableList<String> = ArrayList(providers)
    private var selectedPosition = -1
    private var listener: OnProviderSelectedListener? = null
    private var selectedProvider = ""
    private var selectedApiUrl = ""
    
    init {
        // 设置布局
        val view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_provider_picker, null)
        setContentView(view)
        
        // 初始化控件
        initViews(view)
        
        // 设置标题
        if (!title.isNullOrEmpty()) {
            tvTitle.text = title
        }
        
        // 设置列表
        setupRecyclerView()
        
        // 设置点击事件
        setupClickListeners()
        
        // 设置搜索功能
        setupSearch()
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置软键盘模式为根据需要显示
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
    }
    
    /**
     * 初始化视图组件
     */
    private fun initViews(view: View) {
        recyclerView = view.findViewById(R.id.recycler_view)
        tvTitle = view.findViewById(R.id.tv_title)
        tvCancel = view.findViewById(R.id.tv_cancel)
        tvConfirm = view.findViewById(R.id.tv_confirm)
        etSearch = view.findViewById(R.id.et_search)
    }
    
    /**
     * 设置RecyclerView
     */
    private fun setupRecyclerView() {
        recyclerView.layoutManager = LinearLayoutManager(context)
        val adapter = ProviderAdapter()
        recyclerView.adapter = adapter
    }
    
    /**
     * 设置搜索功能
     */
    private fun setupSearch() {
        etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                // 不需要实现
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 根据搜索文本过滤列表
                s?.let { filterProviders(it.toString()) }
            }

            override fun afterTextChanged(s: Editable?) {
                // 不需要实现
            }
        })
    }
    
    /**
     * 根据关键词过滤服务提供商列表
     */
    private fun filterProviders(query: String) {
        filteredProviders.clear()
        
        if (query.isEmpty()) {
            // 如果查询为空，显示所有提供商
            filteredProviders.addAll(allProviders)
        } else {
            // 否则过滤匹配的提供商
            val lowerCaseQuery = query.toLowerCase()
            for (provider in allProviders) {
                if (provider.toLowerCase().contains(lowerCaseQuery)) {
                    filteredProviders.add(provider)
                }
            }
        }
        
        // 刷新列表
        recyclerView.adapter?.notifyDataSetChanged()
    }
    
    /**
     * 设置点击事件
     */
    private fun setupClickListeners() {
        // 取消按钮
        tvCancel.setOnClickListener { dismiss() }
        
        // 确定按钮
        tvConfirm.setOnClickListener {
            confirmSelection()
        }
        
        // 添加根视图的点击监听，点击空白区域隐藏软键盘
        findViewById<View>(R.id.bottom_sheet_root)?.setOnClickListener {
            hideKeyboard()
        }
    }
    
    /**
     * 确认选择
     */
    private fun confirmSelection() {
        if (selectedProvider.isEmpty()) {
            // 如果未选择，提示用户
            if (selectedPosition == -1) {
                // 如果未选择，提示用户
                tvConfirm.isEnabled = false
                return
            }
        }
        
        listener?.let {
            val apiUrl = ApiProviderManager.getApiUrl(selectedProvider)
            it.onProviderSelected(selectedProvider, apiUrl)
        }
        dismiss()
    }
    
    /**
     * 隐藏软键盘
     */
    private fun hideKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
        imm?.let {
            currentFocus?.let { view ->
                it.hideSoftInputFromWindow(view.windowToken, 0)
                view.clearFocus()
            }
        }
    }
    
    /**
     * 预选择提供商
     */
    fun preSelectProvider(provider: String) {
        for (i in filteredProviders.indices) {
            if (filteredProviders[i] == provider) {
                selectedPosition = i
                selectedProvider = provider
                val apiUrl = ApiProviderManager.getApiUrl(provider)
                selectedApiUrl = apiUrl ?: ""
                recyclerView.adapter?.notifyDataSetChanged()
                break
            }
        }
    }
    
    /**
     * 设置服务提供商选择监听器
     */
    fun setOnProviderSelectedListener(listener: OnProviderSelectedListener) {
        this.listener = listener
    }
    
    /**
     * 使用kotlin的函数类型来简化接口
     */
    fun setOnProviderSelectedListener(listener: (provider: String, apiUrl: String?) -> Unit) {
        this.listener = object : OnProviderSelectedListener {
            override fun onProviderSelected(provider: String, apiUrl: String?) {
                listener(provider, apiUrl)
            }
        }
    }
    
    /**
     * 服务提供商选择监听器接口
     */
    interface OnProviderSelectedListener {
        fun onProviderSelected(provider: String, apiUrl: String?)
    }
    
    /**
     * 服务提供商适配器
     */
    private inner class ProviderAdapter : RecyclerView.Adapter<ProviderAdapter.ViewHolder>() {
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_provider, parent, false)
            return ViewHolder(view)
        }
        
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val provider = filteredProviders[position]
            holder.tvProviderName.text = provider
            
            // 设置选中状态
            val isSelected = (position == selectedPosition)
            holder.ivSelected.visibility = if (isSelected) View.VISIBLE else View.GONE
            
            // 点击事件
            holder.itemView.setOnClickListener {
                val oldPosition = selectedPosition
                selectedPosition = position
                
                selectedProvider = provider
                val apiUrl = ApiProviderManager.getApiUrl(provider)
                selectedApiUrl = apiUrl ?: ""
                
                // 更新选中状态
                notifyItemChanged(oldPosition)
                notifyItemChanged(selectedPosition)
                
                // 启用确认按钮
                tvConfirm.isEnabled = true
            }
        }
        
        override fun getItemCount(): Int {
            return filteredProviders.size
        }
        
        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val tvProviderName: TextView = itemView.findViewById(R.id.tv_provider_name)
            val ivSelected: ImageView = itemView.findViewById(R.id.iv_selected)
        }
    }
} 